package com.example.demo.util.beanUtils.utils2;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;

public class LambdaToMapUtils {

    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        for (Long i = 0L; i < 4; i++) {
            User user = new User();
            user.setId(i);
            user.setAge(i);
            user.setName(String.valueOf(i));
            user.setAddress(String.valueOf(i));
            list.add(user);
//			重复值：key相同value不同
            user.setName(String.valueOf(i+1));
            list.add(user);

        }
//		方式一:泛型
//		Map<Long, String> map =tomap(list,User::getId,User::getName,(k2,k1)->k2);
//		方式二：
//		Map<Long, String> map = list.stream().collect(Collectors.toMap(User::getId, User::getName, (k1,k2)->k1));
        Map<Long, String> map =tomap2(list,User::getId,User::getName);//从bean中抽取两个属性，分别作为key,value 分装成map
        System.out.println(map);
    }

    private static <T, K, V> Map<K, V> tomap(List<T> list, Function<? super T, ? extends K> keyMapper,
                                             Function<? super T, ? extends V> valMapper, BinaryOperator<V> mergeFunction) {
//		list 空值判断。。
        Map<K, V> map =list.stream().
                collect(Collectors.toMap(keyMapper, valMapper, mergeFunction));
        return map;
    }

    private static <T, K, V> Map<K, V> tomap2(Collection<T> c, Function<? super T, ? extends K> keyMapper,
                                              Function<? super T, ? extends V> valMapper) {
//		list 空值判断。。
        Map<K, V> map =c.stream().collect(Collectors.toMap(keyMapper, valMapper, (k1, k2)->k2));
        return map;
    }


}

